#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <dfs.h>
#include <errno.h>
#include "dfs_service.h"
#include "dfs_net.h"

#define REPLICAS_FOLDER "/home/cache"

/* prototype */
void touch_cache_dir(void);

/* main function of dfs_start */
void main(int argc,char **argv)
{
	/* Result of the syscall */
	int result;
	

	/* Making the DFS_START call */
	result = dfs_start();

	if (result != OK){
		if(result == ERROR)
			fprintf(stderr,"Error.Unexpected Error Occured.\n");
		else
			fprintf(stderr,"Error.DFS service already initialized.\n");
		exit(0);
	}
	printf("DFS service has been initialized.\n");
	/* creating cache directory */
	touch_cache_dir();
	/* Forking networking process */
	if (fork() == 0){
		/* dfs_net_module child proc */
		sprintf(argv[0],"dfs_net");
		dfs_net_module();
	}
}

/* function that creates cache folder*/
void touch_cache_dir(){
	DIR * cd;
	int s;
	cd = opendir(REPLICAS_FOLDER);
	if(cd == NULL){
		s = mkdir(REPLICAS_FOLDER,S_IRWXU | S_IRWXO);
		if(s == OK)
			printf("DFS cache directory created\n");
		else{
			perror("Error on creating cache directory");
			exit(errno);
		}
	}
}